package org.example.sdpback.utils;

import cn.hutool.json.JSONObject;
import cn.hutool.jwt.JWT;
import cn.hutool.jwt.JWTUtil;
import lombok.extern.slf4j.Slf4j;
import org.example.sdpback.domain.entity.User;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * @className: JwtUtil
 * @author: zxy
 * @date: 2024/11/3 2:31
 * @Version: 1.0
 * @description: token生成解析工具
 **/
@Slf4j
public class JwtUtil {
    private static final String JWT_SECRET = "secret";

    /**
     * 生成token
     * @param user
     * @return
     */
    public static String getToken(User user) {
        Map<String, Object> claims = new HashMap<>();
        claims.put("userId", user.getId());
        claims.put("username", user.getUsername());
        claims.put("createTime", LocalDateTime.now());
        String token = JWTUtil.createToken(claims, JWT_SECRET.getBytes());
        log.info("生成JWT token: {}", token);
        return token;
    }

    /**
     * 校验token是否正确
     * @param token
     * @return
     */
    public static void checkToken(String token) {
        try{
            JWT jwt = JWTUtil.parseToken(token).setKey(JWT_SECRET.getBytes());
            boolean verify = jwt.verify();
        }catch (Exception e){
            throw new RuntimeException("token 错误！");
        }
    }

    /**
     * 根据token获取去用户信息
     * @param token
     * @return
     */
    public static User getTokenUser(String token) {
        JWT jwt = JWTUtil.parseToken(token).setKey(JWT_SECRET.getBytes());
        JSONObject payloads = jwt.getPayloads();
        payloads.remove("createTime");
        User user = new User();
        user.setUsername(payloads.getStr("username"));
        user.setId(payloads.getLong("userId"));
        return user;
    }
}
